package com.main.sales.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常
 */
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalException {
    /**
     * 进行异常处理方法
     *
     * @param sqlex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> ex(SQLIntegrityConstraintViolationException sqlex) {
        log.error(sqlex.getMessage());
        if (sqlex.getMessage().contains("Duplicate entry")) {
            String[] split = sqlex.getMessage().split(" ");
            return R.error(split[2] + " 已存在");
        }
        return R.error("未知错误");
    }

    /**
     * 进行异常处理方法
     *
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> ex(CustomException e) {
        log.error(e.getMessage());
        return R.error(e.getMessage());
    }

}
